<?php
namespace App\Http\Controllers\Open;

use App\Facades\ClientAuth;
use App\Facades\Option;
use App\Http\Controllers\Controller;
use App\Models\Posts;

use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Response;
use Illuminate\Http\Request as ValidateRequest;
use Illuminate\Support\Facades\Validator;

use App\Services\Spider\BaiduDrive;
use App\Services\Spider\TouTiaoDrive;
use App\Services\Spider\ChinasoDrive;
use App\Services\Spider\BingDrive;
use App\Services\Spider\WuzhuisoDrive;

class PostsController extends Controller
{
     /**
     * 获取用户信息
     */
    public function lists(){
        $data = Posts::all()->toArray();
        return Response::returns([
            'status'=>'success',
            'code'=>'200',
            'data'=>$data
        ]);
    }




    // http://wiki.20wy.cn:8082/web-api/open/post/spider
    public function spider() {
        $keyword = Request::input('keyword');
        if ($keyword=='') $keyword='打工人';
        $count = $this->filterKeyWordCount($keyword);
        if ($count>0 && 0 ) {
            $respData = $this->getPosts($keyword);
            return Response::returns([
                'status'=>'success',
                'code'=>'200',
                'data'=>$respData
            ]);
        }
        $wuzhuisoDrive = new WuzhuisoDrive();
        $data =  $wuzhuisoDrive->claws($keyword);
        // $drive = new BaiduDrive();
        // $data =  $drive->claws($keyword);
        if (!$data || !$data['lists']) {
            return Response::returns([
                'status'=>'error',
                'code'=>'1000',
                'msg'=>'暂无收录您的问题',
            ]);
        }
        if (cacheDataHandle() && $count==0 || 1) {
            $titles = [];
            $short_articles = [];
            foreach($data['lists'] as $k2=>$v2) {
                if ($v2['title'] && $v2['short_article']) {
                    $titles[] = $v2['title'];
                    $short_articles[] = $v2['short_article'];
                } else {
                    unset($data['lists'][$k2]);
                }
            }
            if (0==$this->filterKeyWordCount($keyword)) {
                if ($titles) {
                    $new = [];
                    $new['title'] = json_encode($titles, JSON_UNESCAPED_UNICODE);
                    $new['short_article'] = json_encode($short_articles, JSON_UNESCAPED_UNICODE);
                    $new['footer_url'] = $data['footer_url'] ? json_encode($data['footer_url'], JSON_UNESCAPED_UNICODE) : [];

                    $this->save($keyword, $new);
                }
            }
        }
        $data['lists'] = array_values($data['lists']);
        return Response::returns([
            'status'=>'success',
            'code'=>'200',
            'data'=>$data
        ]);
    }

    public function save($keyword,$data) {
        $post = new Posts();
        $post->title = $data['title'];
        $post->short_article = $data['short_article'];
        $post->footer_url = $data['footer_url']?$data['footer_url']:null;
        $post->keyword = $keyword;
        $client_ip = '';
        if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
            $client_ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
        }

        if (!$client_ip) {
            $client_ip = $_SERVER["REMOTE_ADDR"];
        }
        $post->client_ip = $client_ip;
        $post->created_at = time();
        $post->updated_at = time();

        $post->save();
    }

    public function filterKeyWordCount($keyword) {
       return Posts::where('keyword',$keyword)->count();
    }

    public function getPosts($keyword) {
       $res = Posts::where('keyword',$keyword)->first();
       $titles = json_decode($res->title,true);
       $short_articles = json_decode($res->short_article,true);

       foreach($titles as $k=>$v) {
           $data['lists'][] = [
             'title'=>$titles[$k],
             'short_article'=>$short_articles[$k]
           ];
       }

       $data['footer_url'] = json_decode($res['footer_url'],true);
       return $data;
    }


//    public function callPhantomjs($keyword) {
//        //php取当前的绝对路径
//        if (!$keyword) return ;
//        $current_dir = dirname(dirname(dirname(dirname(dirname(__FILE__)))));
//
//        $exec = "php  ".$current_dir."/phantomjs-framework/index.php {$keyword}";
//
//        $response  = shell_exec($exec);
//
//
//        if (!$response) {
//            return ;
//        }
//        return json_decode($response,true);
//
//    }

}
